#!/bin/bash
# 安装Golang

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_golang() {
    local oldname=`rpm -qa |grep golang`
    local appname="golang-${Version}${GOLANG_END}"
    
    # 检查文件是否已存在
    if [ `ls ${APPS_HOME} | grep ${Version} | wc -l` -ne 3 ];then
        echo "正在下载Golang ${Version}..."
        wget -P ${APPS_HOME} ${GOLANG_NAME}${Version}${GOLANG_END}
        wget -P ${APPS_HOME} ${GOLANG_NAME}bin-${Version}${GOLANG_END}
        wget -P ${APPS_HOME} ${GOLANG_NAME}src-${Version}-0.el7.noarch.rpm 
        
        if [ $? -ne 0 ];then
            error_exit "Golang下载出错"
        fi
    else
        echo "文件已存在，直接使用本地文件"
    fi
    
    # 卸载旧版本
    rpm -qa | grep golang >~/.go_tmp.txt
    for i in `cat ~/.go_tmp.txt`
    do
        rpm -e $i --nodeps 2>/dev/null
    done
    rm -f ~/.go_tmp.txt
    
    # 安装新版本
    cd ${Basedir}/download && ls |grep golang|grep ${Version}|xargs rpm -ivh
    if [ $? -ne 0 ];then
        error_exit "Golang安装失败"
    fi
}

echo "开始安装Golang..."

read -p "输入需要的golang版本(默认1.17.9): " Version
if [ -z "${Version}" ];then
    Version="1.17.9"
    echo "使用默认版本: $Version"
fi

install_golang

# 验证安装
go version
if [ $? -eq 0 ];then
    success_msg "Golang ${Version} 安装成功"
else
    error_exit "Golang ${Version} 安装失败"
fi
